﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using iNet.Tasks;

namespace iNet.Media.Imaging.Filters
{
	/// <summary>
	/// 影像濾鏡工作的基底類別。
	/// </summary>
	public abstract class ImageFilterTask : Task
	{
		#region 欄位
		IImage _ResultImage;
		IImage _SourceImage;
		#endregion
		#region 建構子
		/// <summary>
		/// 初始化新的 ImageFilterTask 執行個體。
		/// </summary>
		protected ImageFilterTask()
		{
			this.InitialProgress = 0;
		}
		/// <summary>
		/// 初始化新的 ImageFilterTask 執行個體。
		/// </summary>
		/// <param name="sourceImage">欲套用濾鏡的影像。</param>
		protected ImageFilterTask(IImage sourceImage)
			: this()
		{
			_SourceImage = sourceImage;
		}
		#endregion
		#region ApplyFilter
		/// <summary>
		/// 套用濾鏡。
		/// </summary>
		/// <param name="version">目前的工作版本。</param>
		/// <param name="sourceImage">欲套用濾鏡的影像。</param>
		/// <param name="resultImage">已套用濾鏡的影像。</param>
		/// <returns>True 表示濾鏡套用成功，False 表示失敗。</returns>
		protected abstract bool ApplyFilter(TaskVersion version, IImage sourceImage, out IImage resultImage);
		#endregion
		#region Execute
		protected override bool Execute(TaskVersion version)
		{
			//取得初始參數
			IImage sourceImage;
			if (!this.ReadValue<IImage>(version, ref _SourceImage, out sourceImage))
				return true;

			//顯示初始訊息及進度
			this.CreateMessage(version, TaskMessageType.Information, Application.Current.Resources["String.ImageFilterTask.Message.ApplyingFilter"] as string);
			this.ReportProgress(version, null);

			//套用濾鏡
			IImage resultImage;
			if (!this.ApplyFilter(version, sourceImage, out resultImage))
				return false;

			//儲存結果
			this.WriteValue<IImage>(version, ref _ResultImage, resultImage);

			//完成
			return true;
		}
		#endregion
		#region OnSourceImageChanged
		/// <summary>
		/// 當來源影像改變時呼叫。
		/// </summary>
		/// <param name="oldSourceImage">舊的來源影像。</param>
		/// <param name="newSourceImage">新的來源影像。</param>
		protected virtual void OnSourceImageChanged(IImage oldSourceImage, IImage newSourceImage)
		{ }
		#endregion
		#region ResultImage
		/// <summary>
		/// 取得已套用濾鏡的影像。
		/// </summary>
		public IImage ResultImage
		{
			get
			{
				return _ResultImage;
			}
		}
		#endregion
		#region SourceImage
		/// <summary>
		/// 取得或設定欲套用濾鏡的影像。
		/// </summary>
		public virtual IImage SourceImage
		{
			get
			{
				return _SourceImage;
			}
			set
			{
				lock (this.SyncRoot)
				{
					IImage oldSourceImage = _SourceImage;
					if (oldSourceImage != value)
					{
						this.SetInitializingParameter<IImage>(ref _SourceImage, value);
						this.OnSourceImageChanged(oldSourceImage, value);
					}
				}
			}
		}
		#endregion
	}
}
